// index.js
// 获取应用实例
const app = getApp()
import {
  API_DOMAIN,getTypeActityId,getActivityList,setActivityList
} from '../../utils/api.config'
Page({
  data: {
    motto: 'Hello ',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'), // 如需尝试获取用户信息可改为false
    inviteCode:'',//邀请人code
    activityId:'',//活动id
    islodding:false,
    wxCode:'',//微信code
    isRoot:false,
    isAgree:false,//同意协议
    isGetPhone:false,
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },

  dicLick() {
    
    wx.redirectTo({
      url: '../activity/index'
    })
  },

  //解析网页参数
	getUrlParam(path,name) {
  

    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = path.substr(1).match(reg); //匹配目标参数
    if(r != null) return unescape(r[2]);
    return null; //返回参数值
  },

goMobile(){
  if(!this.data.isAgree){
    wx.showToast({
      icon: "none",
      title: '请阅读并同意协议！',
    })
    return
  }
  wx.navigateTo({
    url: '/pages/index/mobile',
  })
},

getData(options){
  var tokenId =  wx.getStorageSync( 'tokenId')
  
  if(!tokenId){
    wx.setStorageSync('userData', '');
  }

    if(tokenId){//登录了就跳转活动
      
      wx.switchTab({
        url: '/pages/mine/mine'
      })
          
   
     return
    }

 
  this.getUserCode();
},

  onLoad(options) {
    this.getData(options)
    this.getUserCode()
  },


  isNull :function( str ){
    
    if ( str == "" ) return true ;
    var regu = "^[ ]+$" ;
    var re = new RegExp(regu);
    return re.test(str);
  },    

  loginInto:function(phoneCodeMap){

    
    this.loginUser(phoneCodeMap,this.data.wxCode)

  },

  getUserCode(){
  //   wx.showToast({
  //     title: '加载中，请稍候...',
  //     icon: 'loading',
  //     duration: 20000,
  //     mask:true
  // })
  wx.showLoading();
    var  that = this;
    wx.login({
      success: function (res) {
        
        wx.hideLoading();
    
        var code = res.code;//发送给服务器的code
        var msg =res.userInfo ||{}
        msg.wxCode = code;

        console.log("微信code:"+code)
        
        that.setData({
          wxCode:code
        });
      },
      fail: function (error) {
        wx.hideLoading();

        console.log('login failed ' + error);
        wx.showToast({
          title: '登录失败,请重试！',
          icon: 'none',
          duration: 1000,
          mask:true
      })
      }
    }) 
  },

  loginUser(phoneCodeMap,wxCode){
    var userinfo = wx.getStorageSync('userInfo');

     var user = this.data.userInfo;

   var that = this;
   
   var data ={
        code:wxCode,
        phoneCode:phoneCodeMap.code||'',
        loginAccountType:'WECHAT',
        cloudID:phoneCodeMap.cloudID||'',
        encryptedData:phoneCodeMap.encryptedData||'',
        iv:phoneCodeMap.iv||'',

      }
    

    if(that.data.inviteCode){
      data.inviteUserCode = that.data.inviteCode;
      data.reservationId = that.data.activityId;
    }

    if(user.nickName){
      data.nickName = user.nickName||''
      data.avatar = user.avatarUrl||''
    }
    wx.showToast({
      title: '登录中，请稍候...',
      icon: 'loading',
      duration: 20000,
      mask:true
  })
  
    app.api.weChatLogin(data).then(rest => {
      wx.hideLoading()
      
     
      if(rest&&rest.success){   
        
        wx.setStorageSync('tokenId',rest.data.token);

        app.upDataUserInfo()
        app.isLogin = true
       
      }else{
        wx.showToast({
          title: rest.errMsg||'登录失败,请重试！',
          icon: 'none',
          duration: 2000,
          mask:true
        })
      }
    })
    .catch(r => {
      console.error(r)
      that.getUserCode();

      wx.showToast({
        title: '登录失败,请重试！',
        icon: 'none',
        duration: 2000,
        mask:true
      })
    })
  },

 //通过绑定手机号登录
 getPhoneNumber: function(e) { //点击获取手机号码按钮
  var that = this;


  if (that.userInfo == '') {
    wx.showToast({
      icon: "none",
      title: '请先点击获取用户信息',
    })
    return
  } else {

    console.log("打印用户数据"+JSON.stringify(e))
    var data ={};
    wx.checkSession({
      success: function(res) {
  
        console.log(e.detail.errMsg)
        console.log(e.detail.iv)
        console.log(e.detail.encryptedData)
        var ency = e.detail.encryptedData;

        var code = e.detail.code;
        var iv = e.detail.iv;

        console.log(res)
        

        console.log('打印获取信息：'+ JSON.stringify(e))

        if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
          wx.showModal({
              title: '警告',
              content: '您点击了拒绝授权，部分功能无法使用!',
              showCancel: false,
              confirmText: '返回授权',
              success: function(res) {
                // 用户没有授权成功，不需要改变 isHide 的值
                if (res.confirm) {
                  wx.setStorageSync('enws', '1');
             
                  console.log('用户点击了“返回授权”');
                };
              }
            }),

            
            that.getUserCode();
            that.setData({

              modalstatus: true,

            });
        } else {
  
          //同意授权

            that.loginInto(e.detail);
          return;
         
        }
      },

      fail: function() {

        console.log("session_key 已经失效，需要重新执行登录流程");
        that.getUserCode();

        wx.showToast({
          title: '登录失败,请重试！',
          icon: 'none',
          duration: 2000,
          mask:true
        })
      }

    });
  }
},

  getUserProfile(e) {
    if(!this.data.isAgree){
      wx.showToast({
        icon: "none",
        title: '请阅读并同意协议！',
      })
      return
    }
 
    var that = this;
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        
        console.log(res)
        that.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })

        that.setData({
          isGetPhone:true
        })
      }
    })
  },

  didClickAgree(){
    this.setData({
      isAgree:this.data.isAgree?false:true
    })
  },

  openShare(){//打开微信公众号
 
  },
  didInside(event){

      //   var vt = event.currentTarget.dataset.id ||{};
      // console.log(vt)
      
      // var url = '#/toProPage?protocol='+vt

                                  
      // var url = encodeURIComponent(url) ;

      // wx.navigateTo({
      //   url: '../webview/publicwebview?url=https://www.yuedone.com/h5/privacy.html'
      // })
  
      wx.navigateTo({
         "url": "/pages/outer/outer?webUrl=https://www.yuedone.com/h5/privacy.html"
        //===="url": "/pages/outer/outer?webUrl=http://118.178.181.206/h5/privacy.html"
        
      })
  }


})
